package com.chujian.gateway.filter;

import cn.hutool.core.util.IdUtil;
import com.chujian.framework.auth.SecurityConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author ：chujian
 * @since ：2020-07-29
 * 同一添加请求头，表示请求是从Gateway发出的
 */
@Component
@Slf4j
public class FromGatewayFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getURI().getPath();

        ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate()
                .headers(h -> {
                    // 标记是从网关来的请求
                    h.add(SecurityConst.TOKEN_INNER_MARK_HEADER, IdUtil.fastSimpleUUID());
                    // 设置真实的请求地址
                    h.add(SecurityConst.REAL_REQUEST_URL_HEADER, uri);
                })
                .build();
        ServerWebExchange newExchange = exchange.mutate().request(serverHttpRequest).build();
        return chain.filter(newExchange);
    }

    @Override
    public int getOrder() {
        return 100;
    }
}
